<?php

class WxHelper{
    const TRADETYPE_JSAPI = 'JSAPI',TRADETYPE_NATIVE = 'NATIVE',TRADETYPE_APP = 'APP';
    const URL_UNIFIEDORDER = "https://api.mch.weixin.qq.com/pay/unifiedorder";
    const URL_ORDERQUERY = "https://api.mch.weixin.qq.com/pay/orderquery";
    const URL_CLOSEORDER = 'https://api.mch.weixin.qq.com/pay/closeorder';
    const URL_REFUND = 'https://api.mch.weixin.qq.com/secapi/pay/refund';
    const URL_REFUNDQUERY = 'https://api.mch.weixin.qq.com/pay/refundquery';
    const URL_DOWNLOADBILL = 'https://api.mch.weixin.qq.com/pay/downloadbill';
    const URL_REPORT = 'https://api.mch.weixin.qq.com/payitil/report';
    const URL_SHORTURL = 'https://api.mch.weixin.qq.com/tools/shorturl';
    const URL_MICROPAY = 'https://api.mch.weixin.qq.com/pay/micropay';
    public $error = null;
    public $errorXML = null;
    private $_config;
    public $appid;

    public function __construct($config){
        $this->_config = $config;
        $this->appid = $this->_config["appid"];
    }

    /**
     * JSAPI获取prepay_id
     *
     * @param       $body
     * @param       $out_trade_no
     * @param       $total_fee
     * @param       $notify_url
     * @param       $openid
     * @param array $ext
     *
     * @return null
     */
    public function getPrepayId($body,$out_trade_no,$total_fee,$notify_url,$openid,$ext = null){
        $data = is_array($ext) ? $ext : array();
        $data["body"] = $body;
        $data["out_trade_no"] = $out_trade_no;
        $data["total_fee"] = $total_fee;
        $data["notify_url"] = $notify_url;
        $data["openid"] = $openid;
        $data["trade_type"] = self::TRADETYPE_JSAPI;
        $result = $this->unifiedOrder($data);
        if($result["return_code"] == "SUCCESS" && $result["result_code"] == "SUCCESS"){
            return $result["prepay_id"];
        }else{
            $this->error($result["return_code"] == "SUCCESS" ? $result["err_code_des"] : $result["return_msg"]);
            $this->errorXML = $this->array2xml($result);
            return null;
        }
    }

    /**
     * 扫码支付(模式二)获取支付二维码
     *
     * @param $body
     * @param $out_trade_no
     * @param $total_fee
     * @param $notify_url
     * @param $product_id
     *
     * @return null
     */
    public function getCodeUrl($body,$out_trade_no,$total_fee,$notify_url,$product_id,$ext = null){
        $data = is_array($ext) ? $ext : array();
        $data["body"] = $body;
        $data["out_trade_no"] = $out_trade_no;
        $data["total_fee"] = $total_fee;
        $data["notify_url"] = $notify_url;
        $data["trade_type"] = self::TRADETYPE_NATIVE;
        $data["product_id"] = $product_id;

        $result = $this->unifiedOrder($data);
        //$result["return_code"] = isset($result["return_code"]) ?? 'FAILURE';
        $result["return_code"] = isset($result["return_code"]) ? $result["return_code"] : 'FAILURE';

        //$result["return_msg"] = isset($result["return_msg"]) ?? '';
        $result["return_msg"] = isset($result["return_msg"]) ? $result["return_msg"] : '';

        if($result["return_code"] == "SUCCESS" && $result["result_code"] == "SUCCESS"){
            return $result["code_url"];
        }else{
            $this->error($result["return_code"] == "SUCCESS" ? $result["err_code_des"] : $result["return_msg"]);
            return null;
        }
    }

    function error($error = ''){
        $error && $this->error .= $error . "\r\n";
        return $this->error;
    }

    /**
     * 统一下单接口
     */
    public function unifiedOrder($params,$ext = null){
        $params = array_map('trim',$params);
        if(empty($params['body'])){
            $this->error('body is null !');
            return false;
        }elseif(empty($params['out_trade_no'])){
            $this->error('out_trade_no is null !');
            return false;
        }elseif(empty($params['total_fee'])){
            $this->error('total_fee is null !');
            return false;
        }elseif(empty($params['notify_url'])){
            $this->error('notify_url is null !');
            return false;
        }
        $data = is_array($ext) ? $ext : array();
        $data["body"] = $params['body'];
        $data["out_trade_no"] = $params['out_trade_no'];
        $data["total_fee"] = $params['total_fee'];
        $data["notify_url"] = $params['notify_url'];
        $data["trade_type"] = $params['trade_type'];
        //$data["spbill_create_ip"] = $params['spbill_create_ip'];
        $data["spbill_create_ip"] = $_SERVER['REMOTE_ADDR'];
        $data["appid"] = $this->_config["appid"];
        $data["mch_id"] = $this->_config["mch_id"];
        if($data["trade_type"] == 'JSAPI'){
            if(empty($params['openid'])){
                $this->error('openid is null !');
                return false;
            }
            $data["openid"] = $params['openid'];
        }elseif($data["trade_type"] == 'NATIVE'){
            if(empty($params['product_id'])){
                $this->error('product_id is null !');
                return false;
            }
            $data["product_id"] = $params['product_id'];
        }
        $data["nonce_str"] = $this->get_nonce_string();
        $data["device_info"] = isset($params['device_info']) ? $params['device_info'] : null;//optional
        $data["detail"] = isset($params['detail']) ? $params['detail'] : null; //optional
        $data["attach"] = isset($params['attach']) ? $params['attach'] : null; //optional
        $data["fee_type"] = isset($params['fee_type']) ? $params['fee_type'] : 'CNY';//optional
        $data["time_start"] = isset($params['time_start']) ? $params['time_start'] : null; //optional
        $data["time_expire"] = isset($params['time_expire']) ? $params['time_expire'] : null; //optional
        $data["goods_tag"] = isset($params['goods_tag']) ? $params['goods_tag'] : null;//optional
        $data["limit_pay"] = isset($params['limit_pay']) ? $params['limit_pay'] : null; //optional
        $data["scene_info"] = isset($params['scene_info']) ? $params['scene_info'] : null;//optional
        $result = $this->post(self::URL_UNIFIEDORDER,$data);
        return $result;
    }

    /**
     * 获取jsapi支付所需参数
     */
    public function get_package($prepay_id){
        $data = array();
        $data["appId"] = $this->_config["appid"];
        $data["timeStamp"] = time();
        $data["nonceStr"] = $this->get_nonce_string();
        $data["package"] = "prepay_id=" . $prepay_id;
        $data["signType"] = "MD5";
        $data["paySign"] = $this->sign($data);
        return $data;
    }

    /**
     * 获取发送到通知地址的数据(在通知地址内使用)
     * @return 结果数组，如果不是微信服务器发送的数据返回null
     *          appid
     *          bank_type
     *          cash_fee
     *          fee_type
     *          is_subscribe
     *          mch_id
     *          nonce_str
     *          openid
     *          out_trade_no    商户订单号
     *          result_code
     *          return_code
     *          sign
     *          time_end
     *          total_fee       总金额
     *          trade_type
     *          transaction_id  微信支付订单号
     */
    public function getNotifyData($saveLog = true){
        $xml = file_get_contents("php://input");
        $data = $this->xml2array($xml);
        //$saveLog && sp_log($data,'weixin/' . $this->appid . '/pay/');
        if($this->validate($data)){
            return $data;
        }else{
            return null;
        }
    }

    /**
     * 响应微信支付后台通知
     *
     * @param string $return_code 返回状态码 SUCCESS/FAIL
     * @param        $return_msg  返回信息
     */
    public function responseBack($return_code = "SUCCESS",$return_msg = null){
        $data = array();
        $data["return_code"] = $return_code;
        if($return_msg){
            $data["return_msg"] = $return_msg;
        }
        $xml = $this->array2xml($data);
        print $xml;
    }

    /**
     * 查询订单
     *
     * @param $transaction_id
     * @param $out_trade_no
     *
     * @return array
     */
    public function orderQuery($transaction_id,$out_trade_no){
        $data = array();
        $data["appid"] = $this->_config["appid"];
        $data["mch_id"] = $this->_config["mch_id"];
        $data["transaction_id"] = $transaction_id;
        $data["out_trade_no"] = $out_trade_no;
        $data["nonce_str"] = $this->get_nonce_string();
        $result = $this->post(self::URL_ORDERQUERY,$data);
        return $result;
    }

    /**
     * 关闭订单
     *
     * @param $out_trade_no
     *
     * @return array
     */
    public function closeOrder($out_trade_no){
        $data = array();
        $data["appid"] = $this->_config["appid"];
        $data["mch_id"] = $this->_config["mch_id"];
        $data["out_trade_no"] = $out_trade_no;
        $data["nonce_str"] = $this->get_nonce_string();
        $result = $this->post(self::URL_CLOSEORDER,$data);
        return $result;
    }

    /**
     * 申请退款 - 使用商户订单号
     *
     * @param $out_trade_no 商户订单号
     * @param $out_refund_no 退款单号
     * @param $total_fee 总金额（单位：分）
     * @param $refund_fee 退款金额（单位：分）
     * @param $op_user_id 操作员账号
     *
     * @return array
     */
    public function refund($out_trade_no,$out_refund_no,$total_fee,$refund_fee,$op_user_id){
        $data = array();
        $data["appid"] = $this->_config["appid"];
        $data["mch_id"] = $this->_config["mch_id"];
        $data["nonce_str"] = $this->get_nonce_string();
        $data["out_trade_no"] = $out_trade_no;
        $data["out_refund_no"] = $out_refund_no;
        $data["total_fee"] = $total_fee;
        $data["refund_fee"] = $refund_fee;
        $data["op_user_id"] = $op_user_id;
        $result = $this->post(self::URL_REFUND,$data,true);
        return $result;
    }

    /**
     * 申请退款 - 使用微信订单号
     *
     * @param $transaction_id 微信订单号
     * @param $out_refund_no 退款单号
     * @param $total_fee 总金额（单位：分）
     * @param $refund_fee 退款金额（单位：分）
     * @param $op_user_id 操作员账号
     *
     * @return array
     */
    public function refundByTransId($transaction_id,$out_refund_no,$total_fee,$refund_fee,$op_user_id){
        $data = array();
        $data["appid"] = $this->_config["appid"];
        $data["mch_id"] = $this->_config["mch_id"];
        $data["nonce_str"] = $this->get_nonce_string();
        $data["transaction_id"] = $transaction_id;
        $data["out_refund_no"] = $out_refund_no;
        $data["total_fee"] = $total_fee;
        $data["refund_fee"] = $refund_fee;
        $data["op_user_id"] = $op_user_id;
        $result = $this->post(self::URL_REFUND,$data,true);
        return $result;
    }

    /**
     * 下载对账单
     *
     * @param        $bill_date 下载对账单的日期，格式：20140603
     * @param string $bill_type 类型
     *
     * @return array
     */
    public function downloadBill($bill_date,$bill_type = 'ALL'){
        $data = array();
        $data["appid"] = $this->_config["appid"];
        $data["mch_id"] = $this->_config["mch_id"];
        $data["bill_date"] = $bill_date;
        $data["bill_type"] = $bill_type;
        $data["nonce_str"] = $this->get_nonce_string();
        $result = $this->post(self::URL_DOWNLOADBILL,$data);
        return $result;
    }

    /**
     * 扫码原生支付模式一中的二维码链接转成短链接
     *
     * @param $long_url 需要转换的URL，签名用原串，传输需URLencode
     *
     * @return array
     */
    public function shortUrl($long_url){
        $data = array();
        $data["appid"] = $this->_config["appid"];
        $data["mch_id"] = $this->_config["mch_id"];
        $data["long_url"] = $long_url;
        $data["nonce_str"] = $this->get_nonce_string();
        $data["sign"] = $this->sign($data);
        $data["long_url"] = urlencode($long_url);
        $result = $this->post(self::URL_SHORTURL,$data);
        return $result;
    }

    /**
     * 验证数据签名
     *
     * @param $data 数据数组
     *
     * @return 数据校验结果
     */
    public function validate($data){
        if(!isset($data["sign"])){
            return false;
        }
        $sign = $data["sign"];
        unset($data["sign"]);
        return $this->sign($data) == $sign;
    }

    private function post($url,$data,$cert = false){
        if(!isset($data['sign'])){
            $data['sign_type'] = 'MD5';
            $data["sign"] = $this->sign($data);
        }
        $xml = $this->array2xml($data);
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);
        curl_setopt($ch,CURLOPT_POST,1);
        curl_setopt($ch,CURLOPT_POSTFIELDS,$xml);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
        curl_setopt($ch,CURLOPT_URL,$url);
        if($cert == true){
            if(!file_exists($this->_config["apiclient_cert"])){
                $this->error('apiclient_cert is not exists !');
                return false;
            }elseif(!file_exists($this->_config["apiclient_key"])){
                $this->error('apiclient_key is not exists !');
                return false;
            }
            //使用证书：cert 与 key 分别属于两个.pem文件
            curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM');
            curl_setopt($ch,CURLOPT_SSLCERT,$this->_config['apiclient_cert']);
            curl_setopt($ch,CURLOPT_SSLKEYTYPE,'PEM');
            curl_setopt($ch,CURLOPT_SSLKEY,$this->_config['apiclient_key']);
        }
        $content = curl_exec($ch);
        $array = $this->xml2array($content);
        return $array;
    }

    /**
     * 数据签名
     *
     * @param $data
     *
     * @return string
     */
    private function sign($data){
        ksort($data);
        $string1 = "";
        foreach($data as $k => $v){
            if($v && trim($v) != ''){
                $string1 .= "$k=$v&";
            }
        }
        if(empty($this->_config["pay_apikey"])){
            $this->error('pay_apikey is null !');
            return false;
        }
        $stringSignTemp = $string1 . "key=" . $this->_config["pay_apikey"];
        $sign = strtoupper(md5($stringSignTemp));
        return $sign;
    }

    private function array2xml($array){
        $xml = "<xml>" . PHP_EOL;
        foreach($array as $k => $v){
            if($v && trim($v) != ''){
                $xml .= "<$k><![CDATA[$v]]></$k>" . PHP_EOL;
            }
        }
        $xml .= "</xml>";
        return $xml;
    }

    private function xml2array($xml){
        $array = array();
        $tmp = null;
        try{
            $tmp = (array) simplexml_load_string($xml);
        }catch(Exception $e){
        }
        if($tmp && is_array($tmp)){
            foreach($tmp as $k => $v){
                $array[$k] = (string) $v;
            }
        }
        return $array;
    }

    private function get_nonce_string(){
        return substr(str_shuffle("abcdefghijklmnopqrstuvwxyz0123456789"),0,32);
    }
}